﻿
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static StackExchange.Redis.Role;

namespace HSJM.Service.MWS.Utility
{
    public class StackExchangeConn
    {
        private static ConnectionMultiplexer connection;
        private static readonly object syncObject = new object();

        private static  ConnectionMultiplexer sentinelConnection;
        static ISubscriber sub;
        static ISubscriber sentinelsub;
        public static ConnectionMultiplexer GetFactionConn
        {
            get
            {
                if (connection == null || !connection.IsConnected)
                {
                    lock (syncObject)
                    {
                        var configurationOptions = new ConfigurationOptions()
                        {
                            Password = PubConstant.RedisPass,

                            KeepAlive = 180,
                            ConnectTimeout = 15000,
                            AbortOnConnectFail = true,
                            ResponseTimeout = 15000
                        };
                        foreach (var item in PubConstant.RedisIp)
                        {
                            configurationOptions.EndPoints.Add(item);
                        }

                        connection = ConnectionMultiplexer.Connect(configurationOptions);

                        ConfigurationOptions sentineloption = new ConfigurationOptions();
                        sentineloption.TieBreaker = "";//sentinel模式一定要写

                        foreach (var item in PubConstant.Sentinel)
                        {
                            sentineloption.EndPoints.Add(item);
                        }
                        sentineloption.CommandMap = CommandMap.Sentinel;
                        sentineloption.ServiceName = "mymaster";
                        sentineloption.AbortOnConnectFail = true;
                        //sentinelConnection = connection.GetSentinelMasterConnection(sentineloption);
                        sentinelConnection = ConnectionMultiplexer.Connect(sentineloption);
                        configurationOptions.CommandMap = CommandMap.Sentinel;
                        sentinelsub = connection.GetSubscriber();
                     
                    }
                }
                return connection;
            }
        }

        public static void SubSentinel()
        {  
            sentinelsub.Subscribe("+switch-master", (channel, message) =>
            {

                Console.WriteLine((string)message);
            });
            sentinelsub.Subscribe("messages", (channel, message) =>
            {

                Console.WriteLine((string)message);
            });


            sentinelsub.Publish("messages", "测试订阅消息");

        }
    }
}
